import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swipe_action_cell/core/cell.dart';
import 'package:get/get.dart';
import 'package:xiaofanshu_flutter/controller/recently_message_controller.dart';
import 'package:xiaofanshu_flutter/utils/date_show_util.dart';
import 'package:badges/badges.dart' as badges;
import '../../../static/custom_color.dart';
import 'package:xiaofanshu_flutter/utils/guide_service.dart';
import 'package:xiaofanshu_flutter/config/guide_config.dart';
import 'package:xiaofanshu_flutter/controller/home_controller.dart';
import 'package:xiaofanshu_flutter/utils/toast_util.dart';

class RecentlyMessage extends StatefulWidget {
  const RecentlyMessage({super.key});

  @override
  State<RecentlyMessage> createState() => _RecentlyMessageState();
}

class _RecentlyMessageState extends State<RecentlyMessage> {
  RecentlyMessageController controller = Get.find();

  // 引导相关
  final GlobalKey _likeKey = GlobalKey();
  final GlobalKey _followKey = GlobalKey();
  final GlobalKey _commentKey = GlobalKey();
  GuideController? _guideController;
  bool _hasShownGuide = false;

  @override
  void initState() {
    super.initState();
    
    try {
      _guideController = Get.find<GuideController>();
      
      // ========== 监听引导触发器 ==========
      ever(_guideController!.shouldShowMessageGuide, (shouldShow) {
        if (shouldShow && mounted) {
          Get.log('📢 收到 MessagePage 引导触发信号');
          _hasShownGuide = false; // 重置标志
          
          // 延迟一下，确保UI完全渲染
          Future.delayed(const Duration(milliseconds: 300), () {
            if (mounted) {
              _showGuideIfNeeded();
            }
          });
          
          _guideController?.resetMessageGuideTrigger();
        }
      });
      
      Get.log('✅ MessagePage 引导监听器已设置');
    } catch (e) {
      _guideController = null;
      Get.log('❌ 找不到 GuideController: $e');
    }
    // =====================================
  }

  Future<void> _showGuideIfNeeded() async {
    if (_guideController == null || _hasShownGuide) return;
    
    // 检查全局引导状态
    bool isGuideCompleted = await GuideService.isGuideCompleted();
    if (isGuideCompleted) {
      Get.log('⏭️ 全局引导已完成，跳过 MessagePage 引导');
      _hasShownGuide = true;
      return;
    }
    
    try {
      if (mounted) {
        _hasShownGuide = true;
        await Future.delayed(const Duration(milliseconds: 500));
        
        if (!mounted) return;
        
        final steps = GuideConfig.createMessageGuideTargets(
          likeAndCollectKey: _likeKey,
          followKey: _followKey,
          commentKey: _commentKey,
        );
        
        if (steps.isNotEmpty) {
          GuideService.showGuide(
            context: context,
            steps: steps,
            onFinish: () async {
              Get.log('✅ MessagePage 引导完成');
              await GuideService.setMessageGuideCompleted();
              
              // 切换到我的页面并触发引导
              try {
                final homeController = Get.find<HomeController>();
                await Future.delayed(const Duration(milliseconds: 300));
                homeController.changeIndex(4); // 切换到我的页面
                
                // 触发 MinePage 引导
                await Future.delayed(const Duration(milliseconds: 500));
                _guideController?.triggerMineGuide();
                Get.log('🎯 已触发 MinePage 引导');
              } catch (e) {
                Get.log('❌ 切换页面失败: $e');
              }
            },
            onSkip: () async {
              Get.log('⏭️ 用户跳过 MessagePage 引导');
              await GuideService.setGuideCompleted();
              _guideController?.completeAllGuides();
            },
          );
        }
      }
    } catch (e) {
      Get.log('❌ MessagePage 引导显示失败: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: const Text(
          '消息',
          style: TextStyle(fontSize: 20),
        ),
        centerTitle: true,
      ),
      body: RefreshIndicator(
        onRefresh: () async {
          controller.updateRecentlyMessageList();
        },
        notificationPredicate: (ScrollNotification notification) {
          return true;
        },
        color: CustomColor.primaryColor,
        child: SizedBox(
          height: MediaQuery.of(context).size.height - 56,
          width: double.infinity,
          child: SingleChildScrollView(
            physics: const AlwaysScrollableScrollPhysics(),
            child: Column(
              children: [
                _topMessage(),
                _chatRecentlyMessage(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _topMessage() {
    return Obx(
      () => Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          GestureDetector(
            key: _likeKey,
            onTap: () async {
              await controller.clearPraiseAndCollectionUnreadNum();
              Get.toNamed('/message/praiseAndCollection');
            },
            child: Column(
              children: [
                badges.Badge(
                  showBadge: controller.praiseAndCollectionUnreadNum.value > 0,
                  badgeContent: Text(
                    controller.praiseAndCollectionUnreadNum.value.toString(),
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 10,
                    ),
                  ),
                  badgeAnimation: const badges.BadgeAnimation.scale(),
                  child: Container(
                    height: 50,
                    width: 50,
                    decoration: BoxDecoration(
                      color: const Color(0xfffdeff2),
                      borderRadius: BorderRadius.circular(15),
                    ),
                    child: const Center(
                      child: Icon(
                        Icons.favorite_rounded,
                        color: Color(0xffe9546b),
                        size: 26,
                      ),
                    ),
                  ),
                ),
                const Text(
                  '赞和收藏',
                  style: TextStyle(
                    fontSize: 12,
                    color: Color(0xff595857),
                  ),
                ).marginOnly(top: 5)
              ],
            ),
          ),
          GestureDetector(
            key: _followKey,
            onTap: () async {
              await controller.clearAttentionUnreadNum();
              Get.toNamed('/message/attention');
            },
            child: Column(
              children: [
                badges.Badge(
                  showBadge: controller.attentionUnreadNum.value > 0,
                  badgeContent: Text(
                    controller.attentionUnreadNum.value.toString(),
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 10,
                    ),
                  ),
                  badgeAnimation: const badges.BadgeAnimation.scale(),
                  child: Container(
                    height: 50,
                    width: 50,
                    decoration: BoxDecoration(
                      color: const Color(0xffebf6f7),
                      borderRadius: BorderRadius.circular(15),
                    ),
                    child: const Center(
                      child: Icon(
                        Icons.person,
                        color: Color(0xff38a1db),
                        size: 26,
                      ),
                    ),
                  ),
                ),
                const Text(
                  '新增关注',
                  style: TextStyle(
                    fontSize: 12,
                    color: Color(0xff595857),
                  ),
                ).marginOnly(top: 5)
              ],
            ),
          ),
          GestureDetector(
            key: _commentKey,
            child: Column(
              children: [
                badges.Badge(
                  showBadge: controller.commentUnreadNum.value > 0,
                  badgeContent: Text(
                    controller.commentUnreadNum.value.toString(),
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 10,
                    ),
                  ),
                  badgeAnimation: const badges.BadgeAnimation.scale(),
                  child: Container(
                    height: 50,
                    width: 50,
                    decoration: BoxDecoration(
                      color: const Color(0xffd6e9ca).withOpacity(0.5),
                      borderRadius: BorderRadius.circular(15),
                    ),
                    child: const Center(
                      child: Icon(
                        Icons.maps_ugc,
                        color: Color(0xff68be8d),
                        size: 26,
                      ),
                    ),
                  ),
                ),
                const Text(
                  '评论和@',
                  style: TextStyle(
                    fontSize: 12,
                    color: Color(0xff595857),
                  ),
                ).marginOnly(top: 5)
              ],
            ),
          ),
        ],
      ).paddingOnly(top: 10, bottom: 10),
    );
  }

  Widget _chatRecentlyMessage() {
    return Obx(
      () => Container(
        color: Colors.white,
        child: ListView.builder(
          shrinkWrap: true,
          itemCount: controller.recentlyMessageList.length,
          itemBuilder: (context, index) {
            return GestureDetector(
              onTap: () {
                Get.toNamed('/chat',
                    arguments: controller.recentlyMessageList[index].userId);
              },
              behavior: HitTestBehavior.opaque,
              child: SwipeActionCell(
                key: ObjectKey(index),
                trailingActions: <SwipeAction>[
                  SwipeAction(
                      title: "删除",
                      style: const TextStyle(color: Colors.white, fontSize: 16),
                      onTap: (CompletionHandler handler) async {
                        controller.removeRecentlyMessage(index);
                        handler(true);
                      },
                      color: Colors.red),
                  SwipeAction(
                      title: "已读",
                      style: const TextStyle(color: Colors.white, fontSize: 16),
                      onTap: (CompletionHandler handler) async {
                        controller.readRecentlyMessage(index);
                        handler(false);
                      },
                      color: Colors.orange),
                ],
                child: Row(
                  children: [
                    Container(
                      height: 50,
                      width: 50,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(30),
                        image: DecorationImage(
                          image: NetworkImage(
                              controller.recentlyMessageList[index].avatarUrl),
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 1,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                controller.recentlyMessageList[index].userName,
                                style: const TextStyle(
                                  fontSize: 16,
                                  color: Color(0xff595857),
                                  overflow: TextOverflow.ellipsis,
                                ),
                                maxLines: 1,
                              ),
                              Text(
                                DateShowUtil.showDateWithTime(controller
                                    .recentlyMessageList[index].lastTime),
                                style: const TextStyle(
                                  fontSize: 12,
                                  color: Color(0xffadadad),
                                ),
                              ),
                            ],
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Expanded(
                                flex: 1,
                                child: Text(
                                  controller
                                      .recentlyMessageList[index].lastMessage,
                                  style: const TextStyle(
                                    fontSize: 14,
                                    color: Color(0xffadadad),
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                  maxLines: 1,
                                ),
                              ),
                              controller.recentlyMessageList[index].unreadNum ==
                                      0
                                  ? const SizedBox()
                                  : Container(
                                      height: 20,
                                      width: 20,
                                      decoration: BoxDecoration(
                                        color: const Color(0xffe9546b),
                                        borderRadius: BorderRadius.circular(10),
                                      ),
                                      child: Center(
                                        child: Text(
                                          controller.recentlyMessageList[index]
                                                      .unreadNum >
                                                  99
                                              ? '99+'
                                              : controller
                                                  .recentlyMessageList[index]
                                                  .unreadNum
                                                  .toString(),
                                          style: const TextStyle(
                                            fontSize: 12,
                                            color: Colors.white,
                                          ),
                                        ),
                                      ),
                                    ),
                            ],
                          ),
                        ],
                      ).paddingOnly(left: 10),
                    ),
                  ],
                ).paddingAll(15),
              ),
            );
          },
        ),
      ),
    );
  }
}
